package xkp.lesson.ui;

import xkp.lesson.dao.UserInfoDao;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

public class LoginUi extends JFrame {
    private JTextField userNameText;
    private JPasswordField userPwdText;
    private JButton logBtn;
    private UserInfoDao userInfoDao = new UserInfoDao();

    public LoginUi() {
        //窗体大小
        this.setSize(380,200);
        //设置窗体大小不可改变
        this.setResizable(false);

        //可以退出
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //相对屏幕居中
        this.setLocationRelativeTo(null);
        //窗体名字
        this.setTitle("登录");

        //流式布局
        FlowLayout flow = new FlowLayout();
        this.setLayout(flow);

        JLabel jLabel = new JLabel("欢迎使用爬虫项目");
        jLabel.setPreferredSize(new Dimension(350,30));
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        this.add(jLabel);


        JLabel jl1 = new JLabel("账号：");
        userNameText = new JTextField();
        userNameText.setPreferredSize(new Dimension(300,30));
        JLabel jl2 = new JLabel("密码：");
        userPwdText = new JPasswordField();
        userPwdText.setPreferredSize(new Dimension(300,30));
        this.add(jl1);
        this.add(userNameText);
        this.add(jl2);
        this.add(userPwdText);

        //按钮——JButton
        logBtn = new JButton("登录");
        logBtn.setPreferredSize(new Dimension(100,30));
        this.add(logBtn);
        logBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userName = userNameText.getText();
                String userPwd = String.valueOf(userPwdText.getPassword()).trim();
                System.out.println(userName+":"+userPwd);
                try {
                    if(userInfoDao.login(userName,userPwd)!= null){
                       // Read
                        new MainUi();
                        LoginUi.this.setVisible(false);
                    }else{
                        JOptionPane.showMessageDialog(null, "用户名或密码错误");
                    }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }

            }
        });


        //窗体可见，写在add组件之后
        this.setVisible(true);
    }
}
